<?php

// +----------------------------------------------------------------------
// | liftforgames.com [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Author: tangyin <cicicoco321@163.com> QQ:545764358
// +----------------------------------------------------------------------

namespace app\common\model;

use think\facade\Db;
use app\common\model\Common as CommonModel;

class Module extends CommonModel {


    protected $pk = 'id';

    protected $prefix;
    protected $database;
    public function __construct($data = [], $connection = '')
    {
        $this->prefix = config('database.connections.mysql.prefix');//表前缀
        $this->database = config('database.connections.mysql.database');//数据库名

        parent::__construct($data);
    }
    /**
     * index页面数据获取
     * */
    public function tableData($post,$field='*',$isPage = true)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = 20;
        }

        $tableWhere = $this->tableWhere($post);
        $query      = $this
            ->field($field)
            ->where($tableWhere['where'])->whereOr($tableWhere['whereOr'])->order($tableWhere['order']);

        if ($isPage) {
            $list        = $query->paginate([
                'list_rows'=> $limit,//每页数量
                'query' => request()->param(),
            ]);
            $data        = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $page = $list->render();
            $re['count'] = $list->total();
        } else {
            $list        = $query->select();
            $data        = $this->tableFormat($list);         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = count($list);
            $page = [];
        }

        $re['code'] = 1;
        $re['msg']  = '';
        $re['data'] = $data;
        $re['page'] = $page;
        return $re;
    }


    protected function tableWhere($post)
    {
        $where = $whereOr = [];

        if(isset($post['title']) && !empty($post['title'])){
            $where[] = ['title','like','%'.$post['title'].'%'];
        }
        if(isset($post['name']) && !empty($post['name'])){
            $where[] = ['name','=',$post['name']];
        }
        if(isset($post['status']) && !empty($post['status'])){
            $where[] = ['status','=',$post['status']];
        }
        if(isset($post['type']) && !empty($post['type'])){
            $where[] = ['type','=',$post['type']];
        }

        $result['where']   = $where;
        $result['whereOr'] = $whereOr;

        $result['field'] = "*";
        $pk = $this->pk;
        $result['order'] = [$pk => 'asc'];
        return $result;
    }

    protected function tableFormat($list)
    {
        $moduleType = config("app.moduleType");
        $moduleEmptyTable = config("app.moduleEmptyTable");

        foreach($list as $k => $v){
            $list[$k]['add_time'] = date("Y-m-d",$v['add_time']);

            $list[$k]['type_name'] = $moduleType[$v['type']];
            $list[$k]['emptytable_name'] = $moduleEmptyTable[$v['emptytable']];
        }
        return $list;
    }



    public function add($post){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];

        Db::startTrans();
        try {
            //添加到module表中
            $data['title'] = $post['title'];
            $data['name'] = strtolower($post['name']);
            $data['description'] = $post['description'];
            $data['status'] = 1;
            $data['type'] = $post['type'];
            $data['orderid'] = GetOrderID('module');
            $data['add_time'] = time();
            $data['emptytable'] = $post['emptytable'];

            $moduleid = DB::name('module')->insertGetId($data);
            if(!$moduleid){
                Db::rollback();
                $result['msg'] = '模型类添加失败';
                return $result;
            }
            $prefix = config('database.connections.mysql.prefix');//表前缀
            //$database = config('database.connections.mysql.database');//数据库名
            $title = $post['title'];//模型名称
            $tablename = $prefix.$post['name'];//表名
            $emptytable = $post['emptytable'];
            //基本表
            if($emptytable=='0'){
                //创建基本表
                $this->createTable($tablename,1,$title);
                //添加字段表内容
                $field_res = $this -> addFields($moduleid,1);
                if(!$field_res['code']){
                    Db::rollback();
                    $result['msg'] = $field_res['msg'];
                    return $result;
                }

            }else if($emptytable=='1'){ //文章图片表模型
                //创建文章图片表
                $this->createTable($tablename,2,$title);
                //添加字段表内容
                $field_res = $this -> addFields($moduleid,2);
                if(!$field_res['code']){
                    Db::rollback();
                    $result['msg'] = $field_res['msg'];
                    return $result;
                }
            }else if($emptytable=='2'){ //单页模型
                //创建单页表
                $this->createTable($tablename,3,$title);
                //添加字段表内容
                $field_res = $this -> addFields($moduleid,3);
                if(!$field_res['code']){
                    Db::rollback();
                    $result['msg'] = $field_res['msg'];
                    return $result;
                }
            }

            //权限表增加权限
            if($post['type'] == 1){ //栏目管理
                $pid = 60;
            }else{
                $pid = 29;
            }

            $name = strtolower($post['name']);
            $roledata['pid'] = $pid;
            $roledata['name'] = $post['title'].'管理';
            $roledata['icon'] = 'fa-align-justify';
            $roledata['href'] = 'admin/'.$name.'/list';
            $roledata['right'] = $name.'@list,'.$name.'@add,'.$name.'@edit,'.$name.'@delete,'.$name.'@changeStatus,'.$name.'@changeOrderid';
            $roledata['sort'] = 100;
            $roledata['add_time'] = time();
            $roledata['module_id'] = $moduleid;

            $SystemMenu = new SystemMenu();
            $sm_res = $SystemMenu -> insertGetId($roledata);
            if(!$sm_res){
                Db::rollback();
                $result['msg'] = "权限表添加失败";
                return $result;
            }

            Db::commit();
            adminLog("模型添加",$moduleid);
            $result['code'] = 1;
            $result['msg'] = '模型添加成功';
            return $result;
        } catch (\Exception $e) {
            Db::rollback();
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /**
     * 创建表
     * $tablename 表名
     * $type 1=基本表
     */
    public function createTable($tablename,$type,$title){
        //基本表
        if($type == 1){
            Db::execute("CREATE TABLE `".$tablename."` (
        			  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                      `siteid` int(11) unsigned NOT NULL DEFAULT '1' COMMENT '站点id',
        			  `catid` smallint(5) unsigned COMMENT '所属栏目id',
        			  `userid` int(8) unsigned COMMENT '用户id',
        			  `title` varchar(150) COMMENT '标题',
        			  `picurl` varchar(255)  COMMENT '缩略图片',
        			  `keywords` varchar(255) COMMENT '关键词',
        			  `description` mediumtext COMMENT '摘要',
        			  `content` text COMMENT '详细内容',
        			  `status` int(11) unsigned COMMENT '状态 1=开启，2=关闭',
        			  `orderid` int(11) unsigned COMMENT '排列排序',
        			  `hits` int(11) unsigned COMMENT '点击次数',
        			  `add_time` int(11) unsigned COMMENT '添加时间',
        			  `update_time` int(11) unsigned COMMENT '修改时间',
        			  PRIMARY KEY (`id`),
        			  KEY `status` (`id`,`status`,`orderid`),
        			  KEY `catid` (`id`,`catid`,`status`),
        			  KEY `orderid` (`id`,`catid`,`status`,`orderid`)
        			)  ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT '$title'");
        }else if($type == 2){
            //文章图片表
            Db::execute("CREATE TABLE `".$tablename."` (
                      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                      `siteid` smallint(5) unsigned NOT NULL DEFAULT '1' COMMENT '站点id',
                      `catid` smallint(5) unsigned  COMMENT '所属栏目id',
                      `userid` int(8) unsigned COMMENT '用户id',
                      `title` varchar(150)  COMMENT '标题',
                      `source` varchar(50)  COMMENT '文章来源',
                      `author` varchar(50)  COMMENT '作者编辑',
                      `linkurl` varchar(255) COMMENT '跳转链接',
                      `keywords` varchar(255) COMMENT '关键词',
                      `description` mediumtext COMMENT '摘要',
                      `content` text COMMENT '详细内容',
                      `picurl` varchar(255) COMMENT '缩略图片',
                      `picarr` text COMMENT '组图',
                      `hits` int(11) unsigned COMMENT '点击次数',
                      `orderid` int(11) unsigned COMMENT '排列排序',
                      `add_time` int(11) unsigned COMMENT '添加时间',
        			  `update_time` int(11) unsigned COMMENT '修改时间',
                      `status` int(11) unsigned COMMENT '状态 1=开启，2=关闭',
                      PRIMARY KEY (`id`),
                      KEY `status` (`id`,`status`,`orderid`),
        			  KEY `catid` (`id`,`catid`,`status`),
        			  KEY `orderid` (`id`,`catid`,`status`,`orderid`)
                    ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT '$title';");
        }else if($type == 3){
            Db::execute("CREATE TABLE `".$tablename."` (
                      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                      `siteid` smallint(5) unsigned NOT NULL DEFAULT '1' COMMENT '站点id',
                      `catid` smallint(5) unsigned  COMMENT '所属栏目id',
                      `userid` int(8) unsigned COMMENT '用户id',
                      `title` varchar(150)  COMMENT '标题',
                      `picurl` varchar(255)  COMMENT '缩略图片',
                      `linkurl` varchar(255) COMMENT '跳转链接',
                      `content` text COMMENT '详细内容',
                      `hits` mediumint(8) unsigned COMMENT '点击次数',
                      `orderid` int(11) unsigned COMMENT '排列排序',
                      `add_time` int(11) unsigned COMMENT '添加时间',
        			  `update_time` int(11) unsigned COMMENT '修改时间',
                      `status` int(11) unsigned COMMENT '审核状态',
                      PRIMARY KEY (`id`)
                    ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT '$title';");

        }

    }


    /**
     * 添加字段表内容
     * $moduleid module表id
     * $type 1=基本表
    */
    public function addFields($moduleid,$type){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $Fields = new Fields();

        if($type == 1){ //基本表
            //catid=栏目id,
            //title=标题,
            //picurl=缩略图,
            //keywords=关键词,
            //description=简介,
            //content=详细内容,
            //orderid=排列排序,
            //hits=点击次数,
            //add_time=添加时间,
            //update_time=更新时间,
            //status=状态
            $fields_arr = $Fields ->fieldsArr($moduleid,'catid,userid,title,picurl,keywords,description,content,orderid,hits,add_time,update_time,status');
            //$res = $Fields->insertAll($fields_arr);
            foreach ($fields_arr as $k=>$v){
                $v['orderid'] = GetOrderID('fields');
                $Fields -> insert($v);
            }

        }else if($type == 2){ //文章、图片表模型
            //catid=栏目id,
            //title=标题,
            //source=文章来源,
            //author=>作者编辑,
            //linkurl=>跳转链接,
            //keywords=关键词,
            //description=简介,
            //picurl=缩略图,
            //content=>详细内容,
            //picarr=组图,
            //hits=点击次数,
            //orderid=排列排序,
            //add_time=添加时间,
            //update_time=更新时间,
            //status=状态

            $fields_arr = $Fields ->fieldsArr($moduleid,'catid,userid,title,source,author,linkurl,keywords,description,picurl,content,orderid,picarr,hits,add_time,update_time,status');
            //$res = $Fields->insertAll($fields_arr);
            foreach ($fields_arr as $k=>$v){
                $v['orderid'] = GetOrderID('fields');
                $Fields -> insert($v);
            }

        }else if($type == 3){ //单页模型
            //title=缩略图,
            //picurl=缩略图,
            //linkurl=跳转链接,
            //content=详细内容,
            //hits=点击次数,
            //orderid=排列排序,
            //add_time=添加时间,
            //update_time=更新时间,
            //status=状态
            $fields_arr = $Fields ->fieldsArr($moduleid,'title,userid,picurl,linkurl,content,hits,orderid,add_time,update_time,status');
            //$res = $Fields->insertAll($fields_arr);
            foreach ($fields_arr as $k=>$v){
                $v['orderid'] = GetOrderID('fields');
                $Fields -> insert($v);
            }
        }

//        if(!$res){
//            $result['msg'] = '字段表添加失败';
//            return $result;
//        }

        $result['code'] = 1;
        $result['msg'] = '字段表添加成功';
        return $result;
    }



	//查找字段是否存在于数据表
    public function field_exist($data){
        $fieldName=$data['field'];
        //$prefix = config('database.connections.mysql.prefix');//表前缀

        $name = $this->where(array('id'=>$data['moduleid']))->value('name');
        $tablename=$this->prefix.$name;
        $Fields=Db::getFields($tablename);
        $ishave = 0;    
        foreach ( $Fields as $key =>$r){
            if($key==$fieldName){
                $ishave=1;
            }
        }
        return $ishave;
    }

    //查询数据库是否存在
    public function is_exist_table($table){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $database = $this->database;
        $prefix = $this->prefix;
        //在数据库中查表是否存在
        $sql = "select table_name from information_schema.tables where table_schema='".$database."' and table_name='".$prefix.$table."'";
        $biao =  DB::query($sql);
        if($biao){
            $msg = $table.'表已存在于数据库中';
            $result['code'] = 1;
            $result['msg'] = $msg;
            return $result;
        }else{
            $msg = $table.'表不存在于数据库中';
            $result['msg'] = $msg;
            return $result;
        }
    }
    
    //在modle类中 处理表添加字段（数据库）
	public function get_tablesql($info,$do){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $type = $info['type'];
        $field_name = $info['name'];
        //下拉多选，只能用varchar
        if($type == 'select'){
            if($info['setup']['options'] == ''){
                $result['msg'] = '选项列表不能为空';
                return $result;
            }


           if($info['setup']['multiple'] == 0){ //多选
               if($info['setup']['fieldtype'] != "varchar"){
                   $result['msg'] = '多选列表框只能使用varchar类型';
                   return $result;
               }
           }
        }
		//字段类型
        $fieldtype = $info['type'];
        if(!empty($info['setup']['fieldtype'])){
            $fieldtype=$info['setup']['fieldtype'];
        }
        $field = $info['field'];//字段名
        $name = $this->where(array('id'=>$info['moduleid']))->value('name');//表名

        //在数据库中查表是否存在
        $is_table_res = $this->is_exist_table($name);
        if(!$is_table_res['code']){
            $result['msg'] = $is_table_res['msg'];
            return $result;
        }

        $tablename=$this->prefix.$name;//真实表名
        $maxlength = intval($info['maxlength'])?intval($info['maxlength']):'';//字符长度
        $default=   !empty($info['setup']['default'])?$info['setup']['default']:'';//默认值
        $numbertype = isset($info['setup']['numbertype'])?$info['setup']['numbertype']:0;//1=不包括负数
        $oldfield = isset($info['oldfield'])?$info['oldfield']:'';
        $is_must = '';
        if($info['required'] == 1){ //必填
            $is_must = 'NOT NULL';
        }

//        $result['code'] = 1;
//        $result['data'] = $info['type'];
//        return $result;

        if($do == 'add'){
            $do = 'ADD';
        }else if($do == 'edit'){
            $do =  " CHANGE `".$oldfield."` ";
        }

		switch($fieldtype) {
            case 'varchar':
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);

                if($type == 'select' || $type == 'radio' || $type == 'checkbox'){
                    $options = $info['setup']['options'];
                    $field_name = $field_name."：".$options;
                    $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) ".$is_must." DEFAULT '$default' COMMENT '$field_name'";
                }else{
                    $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) ".$is_must." DEFAULT '$default' COMMENT '$field_name'";
                }
                break;

            case 'title':
                $thumb = $info['setup']['thumb'];
                $style = $info['setup']['style'];
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);
                $sql[] = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) ".$is_must." DEFAULT '$default' COMMENT '$field_name'";


                if(!$this->_iset_field($name,'thumb')){
                    if($thumb==1) {
                        $sql[] = "ALTER TABLE `$tablename` ADD `thumb` VARCHAR( 100 ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                    }
                }else{
                    if($thumb==0) {
                        $sql[] = "ALTER TABLE `$tablename` drop column `thumb` COMMENT '$field_name'";
                    }
                }

                if(!$this->_iset_field($name,'title_style')){
                    if($style==1) {
                        $sql[] = "ALTER TABLE `$tablename` ADD `title_style` VARCHAR( 100 ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                    }
                }else{
                    if($style==0) {
                        $sql[] = "ALTER TABLE `$tablename` drop column `title_style`";
                    }
                }
                break;
            case 'catid':
                $maxlength = $maxlength?$maxlength:5;
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(`$maxlength`) UNSIGNED ".$is_must." DEFAULT '0' COMMENT '$field_name'";
                break;

            case 'number':
                $decimaldigits = $info['setup']['decimaldigits'];
                if($decimaldigits == 0){
                    $fieldtype = "int";
                    $maxlength = 10;
                }else{
                    $fieldtype = "decimal";
                    $maxlength = $decimaldigits;
                }
                $default = $decimaldigits == 0 ? intval($default) : floatval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` ".($decimaldigits == 0 ? 'INT' : 'decimal( 10,'.$decimaldigits.' )')." ".($numbertype ==1 ? 'UNSIGNED' : '')."  NOT NULL DEFAULT '$default' COMMENT '$field_name'";
                break;

            case 'tinyint':
                if(!$maxlength) $maxlength = 3;
                $maxlength = min($maxlength,3);
                $default = intval($default);

                if($type == 'select' || $type == 'radio' || $type == 'checkbox') {
                    $options = $info['setup']['options'];
                    $field_name = $field_name ."：".$options;
                    $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT( $maxlength ) " . ($numbertype == 1 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '$default' COMMENT '$field_name'";
                }else {
                    $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT( $maxlength ) " . ($numbertype == 1 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '$default' COMMENT '$field_name'";
                }
                break;

            case 'smallint':
                $maxlength = 5;
                $default = intval($default);
                if($type == 'select' || $type == 'radio' || $type == 'checkbox') {
                    $options = $info['setup']['options'];
                    $field_name = $field_name ."：".$options;
                    $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT " . ($numbertype == 1 ? 'UNSIGNED' : '') . " " . $is_must . " DEFAULT '$default' COMMENT '$field_name'";
                }else {
                    $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT " . ($numbertype == 1 ? 'UNSIGNED' : '') . " " . $is_must . " DEFAULT '$default' COMMENT '$field_name'";
                }
                break;

            case 'int':
                $maxlength = 10;
                $default = intval($default);

                if($type == 'select' || $type == 'radio' || $type == 'checkbox') {
                    $options = $info['setup']['options'];
                    $field_name = $field_name ."：".$options;
                    $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." ".$is_must." DEFAULT '$default'  COMMENT '$field_name'";

                }else{
                    $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." ".$is_must." DEFAULT '$default' COMMENT '$field_name'";
                }
                break;

            case 'mediumint':
                $maxlength = 8;
                $default = intval($default);
                if($type == 'select' || $type == 'radio' || $type == 'checkbox') {
                    $options = $info['setup']['options'];
                    $field_name = $field_name ."：".$options;
                    $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." ".$is_must." DEFAULT '$default' COMMENT '$field_name'";
                }else{
                    $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." ".$is_must." DEFAULT '$default' COMMENT '$field_name'";
                }
                break;

            case 'longtext':
                $maxlength = 0;
                $sql = "ALTER TABLE `$tablename` $do `$field` LONGTEXT ".$is_must." COMMENT '$field_name'";
                break;

            case 'mediumtext':
                $maxlength = 0;
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT ".$is_must." COMMENT '$field_name'";
                break;

            case 'text':
                $maxlength = 0;
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT ".$is_must." COMMENT '$field_name'";
                break;

            case 'posid':
                $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT(2) UNSIGNED ".$is_must." DEFAULT '0' COMMENT '$field_name'";
                break;

            //case 'typeid':
            //$sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0'";
            //break;
            case 'date':
                if($info['setup']['datetype'] == 'timestamp'){
                    //时间戳
                    $fieldtype = "int";
                    $maxlength = 11;
                }else{
                    $fieldtype = "varchar";
                    $maxlength = $maxlength?$maxlength:30;
                }
                $sql = "ALTER TABLE `$tablename` $do `$field` $fieldtype($maxlength) ".$is_must." DEFAULT '0' COMMENT '$field_name'";

                break;

            case 'datetime':
                if($info['setup']['datetype'] == 'timestamp'){
                    //时间戳
                    $fieldtype = "int";
                    $maxlength = 11;
                }else{
                    $fieldtype = "varchar";
                    $maxlength = $maxlength?$maxlength:30;
                }
                $sql = "ALTER TABLE `$tablename` $do `$field` $fieldtype($maxlength) ".$is_must." DEFAULT '0' COMMENT '$field_name'";
                break;

            case 'editor':
                $maxlength = 0;
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT ".$is_must." COMMENT '$field_name'";
                break;

            case 'image':
                $fieldtype = "varchar";
                if(!$maxlength){ $maxlength = 255;}
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( ".$maxlength." ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                break;

            case 'images':
                $fieldtype = "text";
                $maxlength = 0;
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT ".$is_must." COMMENT '$field_name' COMMENT '$field_name'";
                break;

            case 'file':
                $fieldtype = "varchar";
                $maxlength = 255;
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 255 ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                break;
            case 'video':
                $fieldtype = "varchar";
                $maxlength = 255;
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 255 ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                break;
            case 'files':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT ".$is_must." COMMENT '$field_name'";
                break;
            case 'template':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                break;
            case 'linkage':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) ".$is_must." DEFAULT '' COMMENT '$field_name'";
                break;
            case 'article': //文章采集
                $fieldtype = "text";
                $maxlength = 0;
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT ".$is_must." COMMENT '$field_name'";
                break;
        }
        //DB::execute($sql);
        $result['code'] = 1;
        $result['msg'] = '插入表语句获取成功';
        $result['data'] = [
            'sql'=>$sql,
            'fieldtype'=>$fieldtype,
            'maxlength'=>$maxlength
        ];
        return $result;

    }
		
	//字段添加   字段类型的选择 (模板中)
    public function getTemplateField($type){
        switch($type) {
            case 'title':
                $str = <<<EOT
<div class="layui-form-item" >
	    <label class="layui-form-label" >默认值</label>
	    <div class="layui-input-block" style="width:300px;" >
	      <input  type="text" class="layui-input field-field" lay-verify="required" name="setup[default]" autocomplete="off" placeholder="" >
	    </div>
	  </div>
	 <div class="layui-form-item" >
	    <label class="layui-form-label">是否为密码框</label>
	    <div class="layui-input-inline" >
	      <input type="radio" class="field-ispassword" name="setup[ispassword]" value="1" title="是" checked>
	      <input type="radio" class="field-ispassword" name="setup[ispassword]" value="0" title="否">
	    </div>
	  </div>
EOT;
                return $str;
                break;
        }

    }
		
	
}